import { defineStore } from 'pinia'
import authApi from '@/api/auth'
import authUtil from '@/utils/authUtil'
import { toast } from '@/utils/common'
import router from '@/router/index'

export const useAuthStore = defineStore('authStore', {
    state: () => {
        return {
            markDynamicRoutes: false,
            userInfo: {
                user: {
                    phone: '',
                    nickname: '',
                    avatar: '',
                    email: '',
                    username: ''
                },
                perms: [],
                roles: [],
                routers: []
            }
        }
    },
    getters: {
        getUsername(): string {
            return this.userInfo.user.username
        },
        getNickname(): string {
            return this.userInfo.user.nickname
        },
        getAavtar(): string {
            return this.userInfo.user.avatar
        },
        getRouters(): Array<any> {
            return this.userInfo.routers
        },
        getMarkDynamicRoutes(): boolean {
            return this.markDynamicRoutes
        }
    },
    actions: {
        async login(data: object) {
            const res = await authApi.login(data)
            if ('200' === res.data.code) {
                toast('登录成功')
                authUtil.setToken(res.data.body.token)
                router.push('/')
            }
        },
        async logout() {
            const res = await authApi.logout()
            if ('200' === res.data.code) {
                // 清除 cookie
                authUtil.removeToken()

                // 清空 pinia 状态
                this.userInfo = {
                    user: {
                        phone: '',
                        nickname: '',
                        avatar: '',
                        email: '',
                        username: ''
                    },
                    perms: [],
                    roles: [],
                    routers: []
                }

                // 返回登录页
                router.push('/login')

                toast('您已退出登录')
            }
        },
        async getUserInfo() {
            const res = await authApi.userInfo()
            this.userInfo = res.data.body
        },
        setMarkDynamicRoutes() {
            this.markDynamicRoutes = true
        }
    }
})
